<template>
  <!-- 智能调度系统 -->
  <el-dialog v-model="store.state.isShowCitySmartDispatch"
             title="城市模式"
             top="80px"
             :modal="false"
             style="position: absolute;left: 100px;width:20%;"
             :close-on-click-modal="false"
             append-to-body>
    <el-form :model="form">
      <el-form-item label="城市名称" :label-width="formLabelWidth" >
        <el-input v-model="form.cityName" placeholder="厦门市" autocomplete="off" />
      </el-form-item>
      <el-form-item label="管理区域" :label-width="formLabelWidth">
        <el-select v-model="form.region" placeholder="Please select a zone">
          <el-option label="厦门岛" value="shanghai" />
        </el-select>
      </el-form-item>
      <el-form-item label="开始时间" :label-width="formLabelWidth">
        <el-col :span="30">
          <el-form-item prop="startDate">
            <el-date-picker
                v-model="form.startDate"
                type="date"
                label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
      <el-form-item label="结束时间" :label-width="formLabelWidth">
        <el-col :span="30">
          <el-form-item prop="endDate">
            <el-date-picker
                v-model="form.endDate"
                type="date"
                label="Pick a date"
                placeholder="Pick a date"
                style="width: 100%"
            />
          </el-form-item>
        </el-col>
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialogFormVisible = false">重置</el-button>
         <el-button  v-show="isShowClearCityArea" @click="ClearCityArea">清除区域</el-button>
        <el-button type="primary" @click="isShowCheckDialog"
        >查询</el-button
        >
      </span>
    </template>
  </el-dialog>

  <!--区块标识-->
  <div class="traceClass"
       style="position:absolute;
       margin-top: 10px;
       margin-left: 50%;
       z-index: 100;
       background-color: white;
       height: 50px"
       v-show="isShowDisLabel">
    <ul class="traceClassUl" style="margin: 10px; display: flex;">
      <li class="traceClassLi" >
        <div style="background-color: #4ece2b;width: 15px;height: 15px;margin:10px 8px 10px 15px"></div>
        <span class="PolygonStyle_fillType_05" style="margin: auto;font-size: medium">调入站点</span>
      </li>
      <li class="traceClassLi" >
        <div style="background-color: #ce392b;width: 15px;height: 15px;margin:10px 8px 10px 15px"></div>
        <span class="PolygonStyle_fillType_05" style="margin: auto;font-size: medium">调出站点</span>
      </li>
    </ul>
  </div>

  <!--区域详情-->
  <el-dialog  v-model="store.state.isShowCityXq"
              top="80px"
              class="notice-dialog"
              title="区域详情"
              :modal="false"
              style="position: absolute;right: 40px;width:25%"
              :close-on-click-modal="false">
    <el-form :model="form"  label-position="top">
      <el-form-item label="区块单车数据：" :label-width="formLabelWidth">
        <div style=" width: 100%">
          <el-table :data="tableData"
                    border style="width: 100%"
                    height="180"
                    :cell-style="{textAlign: 'center'}"

                    @row-click="selectByAttribute">
            <el-table-column prop="id" label="ID" width="50"/>
            <el-table-column prop="date" label="Date"  />
            <el-table-column prop="input" label="流入量"  />
            <el-table-column prop="total" label="流出量"  />
            <el-table-column prop="fangan" label="方案"  />
            <el-table-column prop="address" label="地点" />
          </el-table>
        </div>
      </el-form-item>
    </el-form>
    <el-form-item label="供需计算：" :label-width="sformLabelWidth"></el-form-item>
    <el-table :data="inOutData" style="width: 100%">
      <el-table-column prop="Class"  width="150"/>
      <el-table-column prop="Data" label="调动情况"></el-table-column>
    </el-table>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="clearLineLayer">清除路线</el-button>
        <el-button type="primary" @click="getFirstDisLineData"
        >计算路线</el-button
        >
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import "../pages/Map.vue";
import store from '../store/index.js'
import {Vector as VectorSource} from "ol/source";
import {Vector as VectorLayer} from "ol/layer";
import {Fill, Stroke, Style,Icon} from "ol/style";
import MultiLineString from "ol/geom/MultiLineString";
import Point from 'ol/geom/Point';
import View from 'ol/View'
import {getCenter} from "ol/extent";
import axios from "axios";
import WKT from "ol/format/WKT";
import { showLoading, hideLoading } from '../store/loading.js'

/*智能调度对话框*/
const isShowClearCityArea=ref(false)
const dialogFormVisible = ref(false)
const formLabelWidth = '80px'
const sformLabelWidth='100px'
const form = reactive({
  cityName: '',
  region: '',
  startDate: '',
  endDate: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
})
/*城市层面的调度*/
const xmFirstDisVector=ref(null)
const xmFirstDisSource=ref(null)
const firstDisFeature=ref(null)
const firstDisFeatureCube=ref([])
const isGetFirstDisData=ref(false)
//清除城市区域
const ClearCityArea=()=>{
  xmFirstDisSource.value.clear()
  xmFirstDisPointSource.value.clear()
  //隐藏调度标签
  isShowDisLabel.value=false
}

//控制Teissen文本注释
const isShowTeissenText=ref(false)
xmFirstDisSource.value=new VectorSource({})
xmFirstDisVector.value =new VectorLayer({
  name2:'城市层面调度',
  source: xmFirstDisSource.value,
  style:function (feature){
    let input= 'rgba(22,243,92,0.5)'
    let output='rgba(241,75,37,0.5)'
    let _color=input
    if(feature.get('bikeRemain')<0){
      _color=output
    }
    return  new Style({
      fill: new Fill({
        color: _color
      }),
      stroke: new Stroke({
        color: 'rgb(0,0,0)',
        width: 1,
      }),
    })
  }
})
//获取第一层调度区域
const getxmFirstCityData=()=> {
  //展示Loading
  showLoading()
  //控制Teisson文本注释显示与隐藏
  isShowTeissenText.value=true;
  axios.get(store.state.dbApi + '/firstPatchArea').then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetFirstDisData.value)
    {//已获取数据，清空变量
      xmFirstDisSource.value.clear()
      firstDisFeatureCube.value=[]
      //清空表格
      tableData.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmFirstDisVector.value)
      //获取图层名字
      console.log(xmFirstDisVector.value.get('name2'))
      store.state.checkDispatchLayerList.push(xmFirstDisVector.value.get('name2'))
      //激活地图点击事件
      //traceCountMsgEvent()
      //// 初始化地图之后就将弹框挂载好，后续只是修改显示的位置
      //createOverlay()
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      firstDisFeature.value=new WKT().readFeature(getData[i]['multipolygon'])
      //设置属性
      firstDisFeature.value.setProperties({
        name:'firstDispatch',
        id:getData[i]['gid'],
        area:getData[i]['area'],
        o_count:getData[i]['o_count'],
        d_count:getData[i]['d_count'],
        bikeRemain:getData[i]['remain'],
        lng:getData[i]['lng'],
        lat:getData[i]['lat'],
        fangan:getData[i]['fangan']
      })
      firstDisFeatureCube.value.push(firstDisFeature.value)
      //为表格添加数据
      tableData.value.push({
        id:getData[i]['gid'],
        date:'2020-12-21',
        input:getData[i]['d_count'],
        total:getData[i]['o_count'],
        fangan:getData[i]['fangan'],
        address:getData[i]['lng']+','+getData[i]['lat']
      })
    }
    isGetFirstDisData.value=true
    //将线级加载到图源中
    //隐藏Loading
    hideLoading()
    xmFirstDisSource.value.addFeatures(firstDisFeatureCube.value)
  })
}

/**获取第一层站点*/
const xmFirstDisPointVector=ref(null)
const xmFirstDisPointSource=ref(null)
const firstDisPointFeature=ref(null)
const firstDisPointFeatureCube=ref([])
const isGetFirstPointDisData=ref(false)

xmFirstDisPointSource.value=new VectorSource({})
xmFirstDisPointVector.value =new VectorLayer({
  name2:'城市层面调度站点',
  source: xmFirstDisPointSource.value,
  style: new Style({
    image: new Icon({
      scale: 0.08,
      src: "src/assets/站点.svg"
    }),
    })
})
//获取后台第一层调度区域站点
const getxmFirstCityPointData=()=> {
  //控制Teisson文本注释显示与隐藏
  isShowTeissenText.value=true;
  axios.get(store.state.dbApi + '/firstPatchPoint').then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetFirstPointDisData.value)
    {//已获取数据，清空变量
      xmFirstDisPointSource.value.clear()
      firstDisPointFeatureCube.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmFirstDisPointVector.value)
      //获取图层名字
      console.log(xmFirstDisPointVector.value.get('name2'))
      store.state.checkDispatchLayerList.push(xmFirstDisPointVector.value.get('name2'))
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      firstDisPointFeature.value=new WKT().readFeature(getData[i]['point'])
      //设置属性
      firstDisPointFeature.value.setProperties({
        id:getData[i]['gid'],
      })
      firstDisPointFeatureCube.value.push(firstDisPointFeature.value)
    }
    isGetFirstPointDisData.value=true
    //将线级加载到图源中
    xmFirstDisPointSource.value.addFeatures(firstDisPointFeatureCube.value)
  })
}


//可视化第一层单车调度路线
const xmFirstDisLineVector=ref(null)
const xmFirstDisLineSource=ref(null)
const firstDisLineFeatureCube=ref([])
const isGetFirstDisLineData=ref(false)
//控制调度路线图层显示与隐藏
const isShowFirstDisLine=ref(true)
xmFirstDisLineSource.value=new VectorSource({})
xmFirstDisLineVector.value=new VectorLayer({
  name2:'城市层面调度路线',
  source: xmFirstDisLineSource.value,
  style:function(feature){
    var myStyle = [];
    myStyle.push(new Style({
      stroke: new Stroke({
        color: '#e8bc57',
        width: 5,
      }),
    }));
    var linearr = feature.getGeometry().getLineStrings();
    console.log(linearr.length)
    for(let i=0;i<linearr.length;i++){
        linearr[i].forEachSegment(function (start,end){
          var arrowLonLat = [end[0] , end[1]];
          var dx = end[0] - start[0];
          var dy = end[1] - start[1];
          var rotation = Math.atan2(dy, dx);
          //箭头图片样式
          myStyle.push(new Style({
            geometry: new Point(arrowLonLat),
            image: new Icon({
              scale: 0.15,
              src: 'src/assets/箭头右.svg',
              rotateWithView: true,
              rotation: -rotation
            })
          }));
        });
    }
    return myStyle;
  }
  /*new Style({
    stroke: new Stroke({
      color: '#e8bc57',
      width: 4,
    })
  })*/
})
//清除路线图层
const clearLineLayer=()=>{
    //清除
  console.log('清除')
  xmFirstDisLineSource.value.clear()
}
//获取后台路网数据
const getFirstDisLineData=()=> {
  //展示Loading
  showLoading()
  axios.get(store.state.dbApi + '/firstDisLine').then(result => {
    //清空变量/初始化变量
    let getData = [];
    if(isGetFirstDisLineData.value)
    {//已获取数据，清空变量
      xmFirstDisLineSource.value.clear()
      firstDisLineFeatureCube.value=[]
    }else{//还未获取数据，加入图层，初始化图层
      store.state.map.addLayer(xmFirstDisLineVector.value)
      store.state.checkDispatchLayerList.push(xmFirstDisLineVector.value.get('name2'))
    }
    getData = result.data
    //获取数据库数据并通过WKT转换放入图层
    for (let i = 0; i < getData.length; i++) {
      firstDisLineFeatureCube.value.push(new WKT().readFeature(getData[i]['multiline']))
      console.log(getData[i]['multiline'])
    }

    //隐藏Loading
    hideLoading()
    //将线级加载到图源中
    xmFirstDisLineSource.value.addFeatures(firstDisLineFeatureCube.value)
    isGetFirstDisLineData.value=true
  })
}

/*智能调度区域详情*/
/*控制查询结果对话框显示隐藏*/
const isShowDisLabel=ref(false)
const isShowCheckDialog=()=> {
  /*显示第一层调度区域*/
  getxmFirstCityData()
  /*第一层调度区域站点*/
  getxmFirstCityPointData()
  /*显示按钮*/
  isShowClearCityArea.value=true;
  //显示调度标签
  isShowDisLabel.value=true
  let isShow = store.state.isShowCityXq
  if (isShow === true) {
    store.commit('changeIsShowCityXq', false)
  } else {
    store.commit('changeIsShowCityXq', true)
  }
}

//表格
const tableData =ref([])

//供需表格
const inOutData=ref([])
inOutData.value.push(
    {
      Class:'调入站点数',
      Data:521
    },{
      Class:'调出站点数',
      Data:324
    }
)

/**
 * 根据属性高亮选择要素
 * */
const selectdByAttriFeature=ref(null)
const oldSelectdByAttriFeature=ref(null)
const selectByAttribute=(row)=>{
  let features=xmFirstDisVector.value.getSource().getFeatures();
  let ID=1
  let property='id'
  //清除上一个高亮显示
  if(oldSelectdByAttriFeature.value!=null) {
    console.log(oldSelectdByAttriFeature)
    oldSelectdByAttriFeature.value.setStyle(null)
    oldSelectdByAttriFeature.value=null
  }
  for(var i=0,ii=features.length;i<ii;i++){
    if(features[i].get(property)===row.id){
      selectdByAttriFeature.value=features[i];
      break
    }
  }
  oldSelectdByAttriFeature.value=selectdByAttriFeature.value
  selectdByAttriFeature.value.setStyle(
      new Style({
        fill: new Fill({
          color:'rgb(255,255,255,0.4)'
        }),
        stroke: new Stroke({
          color: 'rgb(59,130,229)',
          width: 3,
        }),
      })
  )
  //转到中心点
  let my_view=new View({
    center:getCenter(selectdByAttriFeature.value.getGeometry().getExtent()),
    projection:'EPSG:4326',
    zoom: 12,
  })
  store.state.map.setView(my_view)
}

</script>
<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}

.dialog-footer button:first-child {
  margin-right: 10px;
}

</style>
